package eu.vranckaert.calendar.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import eu.vranckaert.calendar.R;

import java.util.ArrayList;
import java.util.List;

/**
 * User: Dirk Vranckaert
 * Date: 21/02/13
 * Time: 09:58
 */
public class WeekHeaderLayout extends LinearLayout {
    private List<TextView> childeren = new ArrayList<TextView>();

    private int mOffset = 70;

    public WeekHeaderLayout(Context context) {
        this(context, null);
    }

    public WeekHeaderLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WeekHeaderLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs);

        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.WeekHeaderLayout, defStyle, 0);

        mOffset = a.getDimensionPixelSize(R.styleable.WeekHeaderLayout_wh_headerWidth, mOffset);

        a.recycle();
    }

    private void ensureChildren() {
        int childCount = getChildCount();
        if (childCount != 7) {
            throw new IllegalStateException("Must include 7 text-views");
        }

        for (int i=0; i<childCount; i++) {
            View child = getChildAt(i);
            if (!(child instanceof TextView)) {
                throw new IllegalStateException("The layout should only contain text-views");
            }
            childeren.add((TextView)child);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        ensureChildren();

        final int columnWidth = (getWidth() - mOffset) / 7;

        final int count = getChildCount();
        for (int i=0; i<count; i++) {
            TextView child = (TextView) getChildAt(i);

            final int top = 0;
            final int bottom = getHeight();
            final int left = mOffset + (columnWidth * i);
            final int right = left + columnWidth;

            child.layout(left, top, right, bottom);

            child.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
        }
    }
}
